package servlet;

import anno.Autowired;
import anno.RequestBody;
import anno.ResponseBody;
import dao.ShowtimeDAO;
import pojo.Showtime;
import utils.ApiResult;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.Map;

@WebServlet("/showtime")
public class ShowtimeServlet extends BaseServlet {

    @Autowired
    private ShowtimeDAO showtimeDAO;

    /**
     * 添加场次
     *
     * @param req      请求对象
     * @param resp     响应对象
     * @param showtime 场次对象
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult addShowtime(HttpServletRequest req, HttpServletResponse resp, @RequestBody Showtime showtime) throws SQLException {
        showtimeDAO.insert(showtime);
        return new ApiResult(200, "场次添加成功", null);
    }

    /**
     * 更新场次
     *
     * @param req      请求对象
     * @param resp     响应对象
     * @param showtime 场次对象
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult updateShowtime(HttpServletRequest req, HttpServletResponse resp, @RequestBody Showtime showtime) throws SQLException {
        showtimeDAO.update(showtime);
        return new ApiResult(200, "场次更新成功", null);
    }

    /**
     * 删除场次
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @param id   场次ID
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult deleteShowtime(HttpServletRequest req, HttpServletResponse resp, String id) throws SQLException {
        showtimeDAO.deleteById(Integer.parseInt(id));
        return new ApiResult(200, "场次删除成功", null);
    }

    /**
     * 根据ID查询场次
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @param id   场次ID
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult getShowtimeById(HttpServletRequest req, HttpServletResponse resp, String id) throws SQLException {
        Showtime showtime = showtimeDAO.findById(Integer.parseInt(id));
        return new ApiResult(200, "场次查询成功", showtime);
    }

    /**
     * 分页模糊查询场次
     *
     * @param req      请求对象
     * @param resp     响应对象
     * @param keyword  模糊查询关键字
     * @param pageNum  当前页码
     * @param pageSize 每页记录数
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult findShowtimesByPageAndMovieId(HttpServletRequest req, HttpServletResponse resp, String keyword, String pageNum, String pageSize) throws SQLException {
        int page = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        Map<String, Object> result = showtimeDAO.findShowtimesByPageAndMovieId(keyword, page, size);
        return new ApiResult(200, "分页模糊查询场次成功", result);
    }
}